package cn.wen.image;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.widget.Toast;

import com.wen.fileprovider.FileProvider7;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import cn.wen.core.permission.Permission;
import cn.wen.core.permission.PermissionListenerAdapter;
import cn.wen.core.permission.XPermission;


/**
 * 图片选择的一个帮助类
 */

public class ImageHelper {
    // 带过来的Key
    // 是否显示相机的EXTRA_KEY
    public static final String EXTRA_SHOW_CAMERA = "EXTRA_SHOW_CAMERA";
    // 总共可以选择多少张图片的EXTRA_KEY
    public static final String EXTRA_SELECT_COUNT = "EXTRA_SELECT_COUNT";
    public static final String EXTRA_SELECT_ONLY = "EXTRA_SELECT_ONLY";
    // 是否裁剪
    public static final String EXTRA_SELECT_CROP = "EXTRA_SELECT_CROP";
    // 原始的图片路径的EXTRA_KEY
    public static final String EXTRA_DEFAULT_SELECTED_LIST = "EXTRA_DEFAULT_SELECTED_LIST";
    // 选择模式的EXTRA_KEY
    public static final String EXTRA_SELECT_MODE = "EXTRA_SELECT_MODE";
    // 返回选择图片列表的EXTRA_KEY
    public static final String EXTRA_RESULT = "EXTRA_RESULT";
    // 选择图片的模式 - 单选
    public static final int MODE_SINGLE = 0x0012;

    /*****************
     * 获取传递过来的参数
     *****************/
    // 选择图片的模式 - 多选
    public static final int MODE_MULTI = 0x0011;
    public static final int CAMERA_REQUEST_CODE = 0x0033;// 打开相机
    public static final int PHOTO_REQUEST_CODE = 0x0044;// 打开相册
    private Activity mActivity;

    // 最多可以选择多少张图片 - 默认8张
    private int mMaxCount = 9;
    // 选择图片的模式 - 默认多选
    private int mMode = MODE_MULTI;
    // 是否显示拍照的相机
    private boolean mShowCamera = true;
    // 原始的图片
    private ArrayList<String> mOriginData;
    // 就只是选择一张
    private boolean mOnly;
    private boolean mCrop;
    private File mPhotoFile;

    public ImageHelper(Activity activity) {
        this.mActivity = activity;
    }

    public static ImageHelper with(Activity activity) {
        return new ImageHelper(activity);
    }


    /**
     * 单选模式
     */
    public ImageHelper single() {
        mMode = MODE_SINGLE;
        return this;
    }

    /**
     * 单选模式
     */
    public ImageHelper onlySelect() {
        mOnly = true;
        return this;
    }

    public ImageHelper crop(boolean crop) {
        mCrop = crop;
        return this;
    }

    /**
     * 多选模式
     */
    public ImageHelper multi() {
        mMode = MODE_MULTI;
        return this;
    }

    /**
     * 设置可以选多少张图片
     */
    public ImageHelper count(int count) {
        mMaxCount = count;
        return this;
    }

    /**
     * 是否显示相机
     */
    public ImageHelper showCamera(boolean showCamera) {
        mShowCamera = showCamera;
        return this;
    }

    /**
     * 原来选择好的图片
     */
    public ImageHelper origin(ArrayList<String> originList) {
        this.mOriginData = originList;
        return this;
    }


    /**
     * 启动执行 权限6.0自己需要去申请，也可以用我的权限申请框架
     */
    public void start(final OnImageListener imageListener) {
        // 申请权限
        new XPermission(mActivity)
                .permissions(Manifest.permission.READ_EXTERNAL_STORAGE)
                .request(new PermissionListenerAdapter() {
                    @Override
                    public void onSucceed() {
                        Intent intent = new Intent(mActivity, SelectImageActivity.class);
                        addParamsByIntent(intent);
                        SelectImageActivity.setImageListener(imageListener);
                        mActivity.startActivity(intent);
                    }
                });

    }


    /**
     * 给Intent添加参数
     *
     * @param intent
     */
    private void addParamsByIntent(Intent intent) {
        intent.putExtra(EXTRA_SHOW_CAMERA, mShowCamera);
        intent.putExtra(EXTRA_SELECT_ONLY, mOnly);
        intent.putExtra(EXTRA_SELECT_COUNT, mMaxCount);
        if (mOriginData != null && mMode == MODE_MULTI) {
            intent.putStringArrayListExtra(EXTRA_DEFAULT_SELECTED_LIST, mOriginData);
        }
        intent.putExtra(EXTRA_SELECT_MODE, mMode);
    }


    /**
     * 相册
     */
    public void photo(OnImageListener imageListener) {
        count(1).onlySelect().start(imageListener);
    }

    @NonNull
    private Intent getCameraIntent() {
        // 创建文件目录
        createFilePath();
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        // 指定开启系统相机的Action
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri = FileProvider7.getUriForFile(mActivity, mPhotoFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, CAMERA_REQUEST_CODE);
        return intent;
    }

    /**
     * 拍照
     */
    public void camera() {
        new XPermission(mActivity)
                .permissions(Permission.CAMERA)
                .request(new PermissionListenerAdapter() {
                    @Override
                    public void onSucceed() {
                        if (hasCamera()) {
                            // 创建文件目录
                            Intent intent = getCameraIntent();
                            mActivity.startActivityForResult(intent, CAMERA_REQUEST_CODE);
                        } else {
                            Toast.makeText(mActivity, "启动相机失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                });

    }

    /**
     * 创建图片的路径
     */
    public void createFilePath() {
        // 打开相机
        // 创建目录
        // File dir = FileUtils.createCacheDir(mActivity, FileUtils.IMAGE);
        // 创建文件
        File directory = null;
        if (checkSDExist()) {
            directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        }
        if (directory == null) {
            mActivity.getCacheDir();
        }
        if (!directory.exists()) {
            directory.mkdirs();
        }
        mPhotoFile = new File(directory, getFileName());
        if (mPhotoFile != null && !mPhotoFile.exists()) {
            try {
                mPhotoFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // 检查是否SDK准备好
    public static boolean checkSDExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    public String getFileName() {
        return "IMG_" + System.currentTimeMillis() + ".jpg";
    }

    public File getPhotoFile() {
        return mPhotoFile;
    }

    public void setPhotoFile(File mRestorePhotoFile) {
        this.mPhotoFile = mRestorePhotoFile;
    }

    /**
     * 判断系统中是否存在可以启动的相机应用
     *
     * @return 存在返回true，不存在返回false
     */
    public boolean hasCamera() {
        PackageManager packageManager = mActivity.getPackageManager();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    /**
     * 拍照结果处理
     */
    public String cameraResult(Activity activity, int requestCode) {
        String path = null;
        if (requestCode == CAMERA_REQUEST_CODE) {
            // 1.第一个要把图片加到集合
            File photoFile = getPhotoFile();
            if (photoFile.exists() && photoFile.isFile()) {
                path = photoFile.getAbsolutePath();
                // 3.通知系统本地有图片改变，下次进来可以找到这张图片
                activity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(photoFile)));
            }
        }
        return path;
    }

}
